/* ChatActivity.java
 *
 * Copyright 2011 Aleksey Konovalov
 * All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 * 
 */

package org.jimm.app;

import java.util.HashMap;

import org.jimm.db.JimmDatabase.Contacts;
import org.jimm.db.JimmDatabase.History;
import org.jimm.engine.Message;
import org.jimm.im.Account;
import org.jimm.im.Contact;
import org.jimm.service.Preferences;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

public class ChatActivity extends Activity {

	private static final String LOG_TAG = "Jimm:ChatActivity";
	public static final String CONTACT_ID_EXTRA = "ContactID";
	public static final String ACCOUNT_ID_EXTRA = "AccountID";
	

	/** ������� ��� GUI */
	private static final int ADD_HISTORY_ITEM = 0;

	private EditText message;
	private ArrayAdapter<Spannable> historyListAdapter;
	private static HashMap<String, String> cont2mess = new HashMap<String, String>();
	private String contactId;
	private long contactDBId;
	private Account account;
	private Contact contact;
	private boolean insSmile;
	private static boolean NeedClearNotify = true;

	private final Handler mHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case ADD_HISTORY_ITEM:
				historyListAdapter.add(
						ChatMessageFormatter.getFormattedText(
								ChatActivity.this, (Message) msg.obj));
				break;
			}
		}

	};

	private final Contact.Listener contactListener = new Contact.Listener() {

		@Override
		public void onIncomingMessage(String message) {
			contact.setMessagesIsReaded();
			mHandler.sendMessage(mHandler.obtainMessage(ADD_HISTORY_ITEM,
					new Message(message, null, true)));
		}
	};
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat);

		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		NeedClearNotify = true;
		clearNotify(NeedClearNotify);
	
		Intent intent = getIntent();
		contactId = intent.getStringExtra(CONTACT_ID_EXTRA);
		String accountId = intent.getStringExtra(ACCOUNT_ID_EXTRA);
		/*
		 * contactCursor = managedQuery(Contacts.CONTENT_URI, null, Contacts._ID
		 * + " = " + contactDBId, null, null); if (!contactCursor.moveToFirst())
		 * { Log.e(LOG_TAG, "Can't find contact"); finish(); return; }
		 */
		// contactId = contactCursor.getString(contactCursor
		// .getColumnIndex(Contacts.CONTACT_ID));

		account = JimmApplication.getApplication(this).getAccountsManager().getAccount(accountId);

		if (account == null) {
			Log.e(LOG_TAG, "Can't find account");
			finish();
			return;
		}

		contact = account.getContact(contactId);
		if (contact == null) {
			Log.e(LOG_TAG, "contact not found");
			finish();
			return;
		}

		Cursor c = managedQuery(Contacts.CONTENT_URI,
				new String[] { Contacts._ID }, Contacts.CONTACT_ID + " = ?",
				new String[] { contactId }, null);
		if (!c.moveToFirst()) {
			Log.e(LOG_TAG, "Contact not found in DB [contactId = " + contactId + "]");
			finish();
			return;
		}
		contactDBId = c.getLong(0);

		contact.registerListener(contactListener);
		contact.setMessagesIsReaded();
		setTitle(contact.getNick());

		initHistory();

		message = (EditText) findViewById(R.id.InputMessage);

		ImageButton sendButton = (ImageButton) findViewById(R.id.SendButton);
		ImageButton InsertSmile = (ImageButton) findViewById(R.id.InsertSmile);
			
		boolean sendEnter = Preferences.sendEnter;		
		boolean sendButtonHide = Preferences.sendButtonHide;	
		boolean smileButtonHide = Preferences.smileButtonHide;	
		
		if (sendEnter) if (sendButtonHide) sendButton.setVisibility(View.GONE);
		if (smileButtonHide) InsertSmile.setVisibility(View.GONE);
		
	//	final String msg = message.getText().toString().trim();
		
		 
		
		InsertSmile.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SmileOpen();
			}		
		});
		
		
		sendButton.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View view) {
				if (account.isConnected()) {
					String msg = message.getText().toString().trim();
					if (msg.length() > 0) {
						sendMessage(msg);
						message.setText("");
					}
				}
			}
		});
		
		if (sendEnter){
		message.setOnKeyListener(new View.OnKeyListener() {
	    public boolean onKey(View v, int keyCode, KeyEvent event) {
	        if (event.getAction() == KeyEvent.ACTION_DOWN) {
	            if (keyCode == KeyEvent.KEYCODE_ENTER) {
	            	String msg = message.getText().toString().trim();
					if (msg.length() > 0) {
						sendMessage(msg);
						message.setText("");
					}
	                return true;
	            }
	        }
	        return false;
	    }
	});
		}
	}

	protected void clearNotify(boolean act) {
		if (act) {
			NotificationMan.clearNotification(contactId);
			NotificationMan.skipNotifyFrom(contactId);
		} else {
			NotificationMan.revertNotifyFrom(contactId);
		}
	}
	

	
	
	@Override
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	  super.onActivityResult(requestCode, resultCode, data);
	  insSmile=true;
	  if(resultCode==RESULT_OK && requestCode==1){
		  String Smile = data.getStringExtra("MessSmile");
	   message = (EditText) findViewById(R.id.InputMessage);  
	   
	   int start = message.getSelectionStart();
	   int end = message.getSelectionEnd();
	   message.getText().replace(Math.min(start, end), Math.max(start, end),
			   Smile, 0, Smile.length());

	  }}
	
	private void SmileOpen() {     
        Intent intent = new Intent(this, SmileActivity.class);
        startActivityForResult(intent, 1);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		if (contact != null) contact.unregisterListener(contactListener);
		NeedClearNotify=false;
		clearNotify(NeedClearNotify);
	}
	
	@Override
	public void onPause() {
		super.onPause();
		NeedClearNotify=false;
		clearNotify(NeedClearNotify);
		String msg = message.getText().toString().trim();
		cont2mess.put(contactId, msg);
	}

	@Override
	public void onResume() {
		super.onResume();
		NeedClearNotify=true;
		clearNotify(NeedClearNotify);
		String msg = cont2mess.get(contactId);
		if (!insSmile) message.setText(msg);	
		cont2mess.put(contactId, null);
	}
	
	private void initHistory() {
		historyListAdapter = new ArrayAdapter<Spannable>(this,
				R.layout.chat_history_item);

		Cursor c = managedQuery(
				History.CONTENT_URI,
				null,
				History.CONTACT
						+ " = "
						+ contactDBId, null,
				History.DATE + " DESC");

		if (c.moveToLast()) {
			do {
				String text = c.getString(c.getColumnIndex(History.MESSAGE));
				short flags = c.getShort(c.getColumnIndex(History.FLAGS));
				long millis = c.getLong(c.getColumnIndex(History.DATE));

				Time time = new Time();
				time.set(millis);

				Message msg = new Message(text, time,
						(flags & History.FLAG_RECEIVED_MESSAGE) != 0);
				historyListAdapter.add(ChatMessageFormatter.getFormattedText(
						ChatActivity.this, msg));
			} while (c.moveToPrevious());
		}

		ListView history = (ListView) findViewById(R.id.History);
		history.setAdapter(historyListAdapter);
	}

	void sendMessage(String message) {
		cont2mess.put(contactId, null);
		contact.sendMessage(message);
		ContentValues values = new ContentValues();
		values.put(History.MESSAGE, message);
		values.put(History.CONTACT, contactDBId);
		getContentResolver().insert(History.CONTENT_URI, values);
		Time time = new Time();
		time.setToNow();
		Message msg = new Message(message, time, false);
		mHandler.sendMessage(mHandler.obtainMessage(ADD_HISTORY_ITEM, msg));
	}
}
